package com.xz.purchaseOrder.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xz.apply.domain.PurchaseApply;
import com.xz.apply.domain.PurchaseProductApply;
import com.xz.apply.service.IPurchaseApplyService;
import com.xz.apply.service.IPurchaseProductApplyService;
import com.xz.apply.vo.ConfirmPurchaseApplyVo;
import com.xz.common.annotation.DataScope;
import com.xz.common.config.XzConfig;
import com.xz.common.core.domain.AjaxResult;
import com.xz.common.core.redis.RedisCache;
import com.xz.common.exception.ServiceException;
import com.xz.common.utils.DateUtils;
import com.xz.common.utils.RedisCode;
import com.xz.common.utils.SecurityUtils;
import com.xz.common.utils.StringUtils;
import com.xz.product.service.IProductService;
import com.xz.product.vo.ProductCategoryVo;
import com.xz.purchase.domain.PurchasePrice;
import com.xz.purchase.domain.PurchaseProductParam;
import com.xz.purchase.service.IPurchasePriceService;
import com.xz.purchaseOrder.domain.PurchaseOrder;
import com.xz.purchaseOrder.domain.PurchaseProductOrder;
import com.xz.purchaseOrder.dto.ApplyReorderDto;
import com.xz.purchaseOrder.dto.TerminationPurchaseDto;
import com.xz.purchaseOrder.mapper.PurchaseOrderMapper;
import com.xz.purchaseOrder.service.IPurchaseOrderService;
import com.xz.purchaseOrder.service.IPurchaseProductOrderService;
import com.xz.purchaseOrder.vo.PurchaseOrderInfoVo;
import com.xz.purchaseOrder.vo.PurchaseOrderVo;
import com.xz.purchaseOrder.vo.PurchaseProductOrderVo;
import com.xz.purchaseOrder.vo.WaitingListVo;
import com.xz.sales.domain.SalesOrderDetail;
import com.xz.sales.service.ISalesOrderDetailService;
import com.xz.warehouse.domain.Warehouse;
import com.xz.warehouse.service.IWarehouseService;
import common.ECDateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 采购订单Service业务层处理
 *
 * @author xz
 * @date 2024-01-22
 */
@Service
public class PurchaseOrderServiceImpl extends ServiceImpl<PurchaseOrderMapper, PurchaseOrder> implements IPurchaseOrderService {
    @Autowired
    private PurchaseOrderMapper purchaseOrderMapper;
    @Autowired
    private IPurchaseApplyService iPurchaseApplyService;
    @Autowired
    private IPurchaseProductApplyService iPurchaseProductApplyService;
    @Autowired
    private IPurchaseProductOrderService iPurchaseProductOrderService;
    @Autowired
    private IWarehouseService iWarehouseService;
    @Autowired
    private IProductService iProductService;
    @Autowired
    private IPurchasePriceService iPurchasePriceService;
    @Autowired
    private ISalesOrderDetailService iSalesOrderDetailService;
    @Autowired
    private RedisCache redisCache;
    /**
     * 查询采购订单
     *
     * @param id 采购订单主键
     * @return 采购订单
     */
    @Override
    public PurchaseOrderInfoVo selectPurchaseOrderById(Long id) {
        PurchaseOrderInfoVo purchaseOrderInfoVo = purchaseOrderMapper.selectPurchaseOrderById(id);
        if(Objects.nonNull(purchaseOrderInfoVo)){
            List<PurchaseProductOrderVo> productOrderVoList = purchaseOrderInfoVo.getProductOrderVoList();
            for(PurchaseProductOrderVo productApplyVo :productOrderVoList){

                List<PurchaseProductParam> purchaseProductParamList =new ArrayList<>();
                String productParam = productApplyVo.getProductParam();
                if(Objects.nonNull(productParam)){
                    List<String> list = Arrays.asList(productParam.split(";"));
                    for(String params:list){
                        String[] split = params.trim().split(":");
                        if(split.length==2){
                            PurchaseProductParam purchaseProductParam=new PurchaseProductParam();
                            purchaseProductParam.setAttributeName(split[0].trim());
                            purchaseProductParam.setAttributeParameter(split[1].trim());
                            purchaseProductParamList.add(purchaseProductParam);
                        }
                    }
                }
                productApplyVo.setPurchaseProductParamList(purchaseProductParamList);

                // 由于客户老是反馈患者名称对不上，所以子数据改为实时查患者名称。而主数据的患者名称，改为从子数据收集组成逗号分割的字符串即可。
                String patientNames = productOrderVoList.stream()
                        .map(PurchaseProductOrderVo::getPatientName).distinct().collect(Collectors.joining());
                purchaseOrderInfoVo.setPatientName(patientNames);
            }
        }
        return purchaseOrderInfoVo;
    }

    /**
     * 查询采购订单列表
     *
     * @param purchaseOrder 采购订单
     * @return 采购订单
     */
    @DataScope(deptAlias = "d", userAlias = "u")
    @Override
    public List<PurchaseOrderVo> selectPurchaseOrderList(PurchaseOrder purchaseOrder) {
        return purchaseOrderMapper.selectPurchaseOrderList(purchaseOrder);
    }

    /**
     * 新增采购订单
     *
     * @param purchaseOrder 采购订单
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult insertPurchaseOrder(PurchaseOrder purchaseOrder) {

        List<PurchaseProductOrder> orderProductOrderList = purchaseOrder.getProductOrderList();
        if(CollectionUtils.isEmpty(orderProductOrderList)){
            return AjaxResult.error("参数不能为空");
        }

        purchaseOrder.setPurchaseNo(RedisCode.getCode("CG"));
        purchaseOrder.setCreateTime(DateUtils.getNowDate());
        purchaseOrder.setCreateBy(SecurityUtils.getUserId());
        purchaseOrder.setTenantId(SecurityUtils.getLoginUser().getTenantId());
        //自主采购订单
        purchaseOrder.setPurchaseType(3);
        // 填充单据的仓库为所属部门（门店）
        Warehouse warehouse = iWarehouseService.getById(purchaseOrder.getWarehouseId());
        if(Objects.isNull(warehouse)){
          return AjaxResult.error("仓库不存在");
        }
        purchaseOrder.setDeptId(warehouse.getDeptId());
        purchaseOrder.setWarehouseAddress(warehouse.getAddress());

        int insertPurchaseOrder = baseMapper.insertPurchaseOrder(purchaseOrder);
        if(insertPurchaseOrder>0){
            List<PurchaseProductOrder> productOrderList=new ArrayList<>();
            dataProductOrder(purchaseOrder,productOrderList,orderProductOrderList);
            if(!CollectionUtils.isEmpty(productOrderList)){
                boolean savedBatch = iPurchaseProductOrderService.saveBatch(productOrderList);
                if(!savedBatch){
                    throw new ServiceException("新增采购订单失败");
                }
                if(purchaseOrder.getPurchaseType()==2&&purchaseOrder.getStatus()==2){
                    productOrderList.stream().forEach(item->{
                        PurchaseProductApply purchaseProductApply = iPurchaseProductApplyService.selectPurchaseProductApplyById(item.getPurchaseDetailId());
                        if(Objects.nonNull(purchaseProductApply)&& purchaseProductApply.getBizDetailId()!=null){
                            //todo 采购中
                            SalesOrderDetail salesOrderDetail =new SalesOrderDetail();
                            salesOrderDetail.setId(purchaseProductApply.getBizDetailId());
                            salesOrderDetail.setProductStatus(5);
                            iSalesOrderDetailService.updateSalesOrderDetail(salesOrderDetail);
                        }
                    });
                }


                return AjaxResult.success("新增采购订单成功");
            }
            return AjaxResult.error("新增采购订单失败");
        }
        return AjaxResult.error("新增采购订单失败");
    }

    /**
     * 修改采购订单
     *
     * @param purchaseOrder 采购订单
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult updatePurchaseOrder(PurchaseOrder purchaseOrder) {
        if(purchaseOrder.getId()==null){
            return AjaxResult.error("参数id不能为空");
        }
        List<PurchaseProductOrder> purchaseProductOrderList = purchaseOrder.getProductOrderList();
        if(CollectionUtils.isEmpty(purchaseProductOrderList)){
            return AjaxResult.error("参数不能为空");
        }
        //仓库所属部门
        Warehouse warehouse = iWarehouseService.getById(purchaseOrder.getWarehouseId());
        if(Objects.isNull(warehouse)){
            return AjaxResult.error("仓库不存在");
        }
        purchaseOrder.setDeptId(warehouse.getDeptId());
        purchaseOrder.setUpdateTime(DateUtils.getNowDate());
        purchaseOrder.setUpdateBy(SecurityUtils.getUserId());
        int updatePurchase = purchaseOrderMapper.updatePurchaseOrder(purchaseOrder);
        if(updatePurchase>0){
            List<PurchaseProductOrder> productOrderList=new ArrayList<>();
            //删除采购订单商品信息
            iPurchaseProductOrderService.deletePurchaseProductOrderById(purchaseOrder.getId());
            dataProductOrder(purchaseOrder,productOrderList,purchaseProductOrderList);
            if(!CollectionUtils.isEmpty(productOrderList)){
                boolean savedBatch = iPurchaseProductOrderService.saveBatch(productOrderList);
                if(!savedBatch){
                    throw new ServiceException("修改采购订单失败");
                }
                if(purchaseOrder.getPurchaseType()==2&&purchaseOrder.getStatus()==2){
                    productOrderList.stream().forEach(item->{
                        PurchaseProductApply purchaseProductApply = iPurchaseProductApplyService.selectPurchaseProductApplyById(item.getPurchaseDetailId());
                        if(Objects.nonNull(purchaseProductApply)&& purchaseProductApply.getBizDetailId()!=null){
                            SalesOrderDetail salesOrderDetail =new SalesOrderDetail();
                            salesOrderDetail.setId(purchaseProductApply.getBizDetailId());
                            salesOrderDetail.setProductStatus(5);
                            iSalesOrderDetailService.updateSalesOrderDetail(salesOrderDetail);
                        }
                    });
                }
                return AjaxResult.success("修改采购订单成功");
            }
            return AjaxResult.error("修改采购订单失败");
        }
        return AjaxResult.error("修改采购订单失败");
    }

    /**
     * 批量删除采购订单
     *
     * @param ids 需要删除的采购订单主键
     * @return 结果
     */
    @Override
    public int deletePurchaseOrderByIds(Long[] ids) {
        return purchaseOrderMapper.deletePurchaseOrderByIds(ids);
    }

    /**
     * 采购终止
     *
     * @param id 采购订单主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult deletePurchaseOrderById(Long id) {
        PurchaseProductOrder purchaseProductOrder = iPurchaseProductOrderService.selectPurchaseProductOrderById(id);
        if(Objects.isNull(purchaseProductOrder)){
            return AjaxResult.error("采购订单不存在");
        }
        iPurchaseProductOrderService.updatePurchaseProductOrderStatus(id);
        PurchaseOrder order = baseMapper.selectById(purchaseProductOrder.getPurchaseOrderId());
        if(Objects.isNull(order)){
            return AjaxResult.error("采购订单不存在");
        }
        if(order.getPurchaseType()!=3){
            Long purchaseDetailId = purchaseProductOrder.getPurchaseDetailId();
            int status = iPurchaseProductApplyService.updatePurchaseProductStatus(purchaseDetailId);
            if(status==0){
                return AjaxResult.error("采购终止失败");
            }
            PurchaseProductApply purchaseProductApply = iPurchaseProductApplyService.getById(purchaseDetailId);
            if(Objects.isNull(purchaseProductApply)){
                return AjaxResult.error("采购终止失败");
            }
            //更新采购申请状态
            PurchaseApply purchaseApply = iPurchaseApplyService.getById(purchaseProductApply.getPurchaseId());

            if(Objects.nonNull(purchaseApply)&&purchaseApply.getProductApplyType()==3&& purchaseProductApply.getBizDetailId()!=null){
                SalesOrderDetail salesOrderDetail =new SalesOrderDetail();
                salesOrderDetail.setId(purchaseProductApply.getBizDetailId());
                salesOrderDetail.setProductStatus(6);
                iSalesOrderDetailService.updateSalesOrderDetail(salesOrderDetail);
            }
        }
        //更新采购申请状态
        int ordercount = iPurchaseProductOrderService.count(new QueryWrapper<PurchaseProductOrder>().eq("purchase_order_id", order.getId()).eq("status", 1));
        if(ordercount==0){
            order.setStatus(4);
            int updatedById = baseMapper.updateById(order);
            if(updatedById==0){
                throw new ServiceException("终止采购失败");
            }
        }
        return AjaxResult.success("终止成功");
    }

    /**
     * 删除
     * @param purchaseDto
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult terminationPurchase(TerminationPurchaseDto purchaseDto) {
        if(purchaseDto.getType()==2){
            if(purchaseDto.getPurchaseProductOrderId() ==null){
                return AjaxResult.error("参数不能为空");
            }
            PurchaseProductOrder productOrder = iPurchaseProductOrderService.selectPurchaseProductOrderById(purchaseDto.getPurchaseProductOrderId());
            if(Objects.isNull(productOrder)){
                return AjaxResult.error("商品不存在");
            }
            productOrder.setStatus(3);
            productOrder.setUpdateTime(DateUtils.getNowDate());
            productOrder.setUpdateBy(SecurityUtils.getUserId());
            boolean updateById = iPurchaseProductOrderService.updateById(productOrder);
            if(updateById){
                PurchaseOrder order = baseMapper.selectById(productOrder.getPurchaseOrderId());
                if(Objects.isNull(order)){
                    return AjaxResult.error("采购订单不存在");
                }
                //更新采购申请状态
                int count = iPurchaseProductOrderService.count(new QueryWrapper<PurchaseProductOrder>().eq("purchase_order_id", productOrder.getPurchaseOrderId()).eq("status", 1));
                if(count==0){
                    order.setStatus(3);
                    int updatedById = baseMapper.updateById(order);
                    if(updatedById==0){
                        throw new ServiceException("终止采购失败");
                    }
                }
                PurchaseProductApply purchaseProductApply = iPurchaseProductApplyService.selectPurchaseProductApplyById(productOrder.getPurchaseDetailId());
                if(Objects.isNull(purchaseProductApply)){
                    throw new ServiceException("终止采购失败");
                }
                purchaseProductApply.setPurchaseNum(purchaseProductApply.getPurchaseNum()+productOrder.getPurchaseNum());
                purchaseProductApply.setStatus(1);
                iPurchaseProductApplyService.updatePurchaseProductApply(purchaseProductApply);
                //更新采购申请状态
                int count1 = iPurchaseProductApplyService.count(new QueryWrapper<PurchaseProductApply>().eq("purchase_id", purchaseProductApply.getPurchaseId()).eq("status", 1));
                PurchaseApply purchaseApply = iPurchaseApplyService.getById(purchaseProductApply.getPurchaseId());
                purchaseApply.setPurchaseStatus(1);
                iPurchaseApplyService.updateById(purchaseApply);
                if (Objects.nonNull(purchaseApply) && purchaseApply.getProductApplyType() == 3 && purchaseProductApply.getBizDetailId() != null) {
                  SalesOrderDetail salesOrderDetail = new SalesOrderDetail();
                  salesOrderDetail.setId(purchaseProductApply.getBizDetailId());
                  salesOrderDetail.setProductStatus(4);
                  iSalesOrderDetailService.updateSalesOrderDetail(salesOrderDetail);
                }
                return AjaxResult.success("终止采购成功");
            }
        }else{
            List<PurchaseProductOrder> productOrders = iPurchaseProductOrderService.list(new QueryWrapper<PurchaseProductOrder>().eq("purchase_order_id", purchaseDto.getPurchaseOrderId()).eq("status", 1));
            productOrders.stream().forEach(productOrder->{
                productOrder.setStatus(3);
                productOrder.setUpdateTime(DateUtils.getNowDate());
                productOrder.setUpdateBy(SecurityUtils.getUserId());
            });
            iPurchaseProductOrderService.updateBatchById(productOrders);
            PurchaseOrder order = baseMapper.selectById(purchaseDto.getPurchaseOrderId());
            if(Objects.isNull(order)){
                return AjaxResult.error("采购订单不存在");
            }
            order.setStatus(3);
            int updatedById = baseMapper.updateById(order);
            if(updatedById==0){
                throw new ServiceException("终止采购失败");
            }
            productOrders.stream().forEach(productOrder->{
                PurchaseProductApply purchaseProductApply = iPurchaseProductApplyService.selectPurchaseProductApplyById(productOrder.getPurchaseDetailId());
                if(Objects.isNull(purchaseProductApply)){
                    throw new ServiceException("终止采购失败");
                }
                purchaseProductApply.setPurchaseNum(purchaseProductApply.getPurchaseNum()+productOrder.getPurchaseNum());
                purchaseProductApply.setStatus(1);
                iPurchaseProductApplyService.updatePurchaseProductApply(purchaseProductApply);
                //更新采购申请状态
                int count1 = iPurchaseProductApplyService.count(new QueryWrapper<PurchaseProductApply>().eq("purchase_id", purchaseProductApply.getPurchaseId()).eq("status", 1));
                PurchaseApply purchaseApply = iPurchaseApplyService.getById(purchaseProductApply.getPurchaseId());
                purchaseApply.setPurchaseStatus(1);
                iPurchaseApplyService.updateById(purchaseApply);
                if (Objects.nonNull(purchaseApply) && purchaseApply.getProductApplyType() == 3 && purchaseProductApply.getBizDetailId() != null) {
                  SalesOrderDetail salesOrderDetail = new SalesOrderDetail();
                  salesOrderDetail.setId(purchaseProductApply.getBizDetailId());
                  salesOrderDetail.setProductStatus(4);
                  //iSalesOrderDetailService.updateStatus(salesOrderDetail);
                  iSalesOrderDetailService.updateSalesOrderDetail(salesOrderDetail);
                }
            });
            return AjaxResult.success("终止采购成功");
        }




        return AjaxResult.error("终止采购失败");
    }

    /**
     * 门店采购申请转订单
     * @param applyReorderDto
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult applyReorder(ApplyReorderDto applyReorderDto) {
        List<ConfirmPurchaseApplyVo> reorderInfoDtoList = applyReorderDto.getReorderInfoDtoList();
        List<PurchaseProductOrder> productOrderList=new ArrayList<>();
        Map<Long, Map<Long, List<ConfirmPurchaseApplyVo>>> longMapMap = reorderInfoDtoList.stream().collect(Collectors.groupingBy(ConfirmPurchaseApplyVo::getWarehouseId, Collectors.groupingBy(ConfirmPurchaseApplyVo::getSupplierId)));
        for(Map.Entry<Long, Map<Long, List<ConfirmPurchaseApplyVo>>> warehouseEntry:longMapMap.entrySet()){
            //仓库id
            Long warehouseId = warehouseEntry.getKey();
            //仓库所属部门
            Warehouse warehouse = iWarehouseService.getById(warehouseId);
            if(Objects.isNull(warehouse)){
                return AjaxResult.error("仓库不存在");
            }
            for(Map.Entry<Long, List<ConfirmPurchaseApplyVo>> supplierEntry:warehouseEntry.getValue().entrySet()){
                //供应商id
                Long supplierId = supplierEntry.getKey();
                PurchaseOrder order=new PurchaseOrder();
                order.setSupplierId(supplierId);
                order.setWarehouseId(warehouseId);
                order.setPurchaseType(applyReorderDto.getApplyType());
                order.setPurchaseNo(RedisCode.getCode("CG"));
                String warehouseName = null;//仓库名称
                String supplierName = null;//供应商名称
                String purchaseNo = null;//申请单号
                String purchaseApplyId = null;//申请id
                String warehouseAddress = null;//仓库地址
                //Long memberId = null;//客户id
                //String memberName = null;//可不名称

                StringBuilder memberId = new StringBuilder();
                StringBuilder memberName = new StringBuilder();

                Integer num=0;
                for(ConfirmPurchaseApplyVo purchaseApplyVo:supplierEntry.getValue()){
                    if(StringUtils.isEmpty(warehouseName)){
                        warehouseName=purchaseApplyVo.getWarehouseName();
                    }
                    if(StringUtils.isEmpty(supplierName)){
                        supplierName=purchaseApplyVo.getSupplierName();
                    }
                    if(StringUtils.isEmpty(warehouseAddress)){
                        warehouseAddress=purchaseApplyVo.getAddress();
                    }
                    if(StringUtils.isEmpty(purchaseNo)){
                        purchaseNo=purchaseApplyVo.getApplyNumber();
                    }else{
                        if(!purchaseNo.contains(purchaseApplyVo.getApplyNumber())){
                            purchaseNo=purchaseNo+","+purchaseApplyVo.getApplyNumber();
                        }
                    }
                    if(StringUtils.isEmpty(purchaseApplyId)){
                        purchaseApplyId=purchaseApplyVo.getId().toString();
                    }else{
                        purchaseApplyId=purchaseApplyId+","+purchaseApplyVo.getId();
                    }
                    purchaseApplyVo.setPurchaseNo(order.getPurchaseNo());
                    num+=purchaseApplyVo.getPurchaseNum();
                    /*if(memberId==null){
                        memberId=purchaseApplyVo.getPatientId();
                    }
                    if(StringUtils.isEmpty(memberName)){
                        memberName=purchaseApplyVo.getPatientName();
                    }*/

                    memberId.append(",");
                    memberId.append(purchaseApplyVo.getPatientId());
                    memberName.append(",");
                    memberName.append(purchaseApplyVo.getPatientName());
                }
                order.setWarehouseName(warehouseName);
                order.setSupplierName(supplierName);
                order.setPurchaseApplyId(purchaseApplyId);
                order.setRelevancePurchaseNo(purchaseNo);
                order.setWarehouseName(warehouseName);
                order.setDeptId(warehouse.getDeptId());
                order.setCreateTime(DateUtils.getNowDate());
                order.setCreateBy(SecurityUtils.getUserId());
                order.setTenantId(SecurityUtils.getLoginUser().getTenantId());
                order.setPurchaseNum(num);
                order.setStatus(1);
                order.setWarehouseAddress(warehouseAddress);
                //order.setPatientId(memberId);
                //order.setPatientName(memberName);
                order.setPatientId(memberId.substring(1));
                order.setPatientName(memberName.substring(1));
                baseMapper.insertPurchaseOrder(order);
                dataProductOrderReorder(order,productOrderList,supplierEntry.getValue());
            }
        }
        if(!CollectionUtils.isEmpty(productOrderList)){
            boolean savedBatch = iPurchaseProductOrderService.saveBatch(productOrderList);
            if(!savedBatch){
                throw new ServiceException("生成采购单失败");
            }
          // 生成采购单后，如果包含了由定制订单（SalesOrder）发起的采购申请，则需要进行额外操作。
          // 需要就关联单号（销售单号）找到对应商品详情（SalesOrderDetail）,进行状态（productStatus）变更。
          // 由待采购状态改为采购中（productStatus: 3.待采购 >> 4.采购中）。

          if (null != applyReorderDto.getApplyType() && 2 == applyReorderDto.getApplyType().intValue()) {
            productOrderList.stream().forEach(item -> {
              PurchaseProductApply purchaseProductApply = iPurchaseProductApplyService.selectPurchaseProductApplyById(item.getPurchaseDetailId());
              if (Objects.nonNull(purchaseProductApply) && purchaseProductApply.getBizDetailId() != null) {
                //todo 采购中
                SalesOrderDetail salesOrderDetail = new SalesOrderDetail();
                salesOrderDetail.setId(purchaseProductApply.getBizDetailId());
                salesOrderDetail.setProductStatus(5);
                iSalesOrderDetailService.updateSalesOrderDetail(salesOrderDetail);
              }
            });
          }
        }
      // 缓存此次提交的数据中，最后一笔的供应商id
      saveRedisLastSupplierForApply(reorderInfoDtoList);


      return AjaxResult.success("生成采购单成功");
    }

  /**
   * 缓存此次提交的数据中，最后一笔的供应商id
   * @param reorderInfoDtoList
   */
  private void saveRedisLastSupplierForApply(List<ConfirmPurchaseApplyVo> reorderInfoDtoList) {
    // 用户提了个需求：定制采购确认的供应商，默认该商品上次入库的供应商，如没有入库过，则为空。
    // 所以这里要缓存此次提交的数据中，最后一笔的供应商id，以便于前端为下一次要提交的数据赋值“供应商”
    String key = XzConfig.getRedisPrefix() + "applyreorder:lastsupplier:" + SecurityUtils.getUserId();
    Map<String,String> map = new HashMap();
    reorderInfoDtoList.forEach(info->{
      if(null != info.getProductId() && null != info.getSupplierId()){
        map.put(""+info.getProductId(),""+info.getSupplierId());
      }
    });
    redisCache.setCacheMap(key, map);
  }

  /**
     * 申请数据处理--转订单
     * @param order
     * @param productOrderList
     * @param purchaseApplyVoList
     */
    public void dataProductOrderReorder(PurchaseOrder order,List<PurchaseProductOrder> productOrderList,List<ConfirmPurchaseApplyVo> purchaseApplyVoList){
        for(ConfirmPurchaseApplyVo purchaseApplyVo:purchaseApplyVoList) {
            PurchaseProductOrder productOrder = new PurchaseProductOrder();
            //采购会员id与名称
            productOrder.setPatientId(purchaseApplyVo.getPatientId());
            productOrder.setPatientName(purchaseApplyVo.getPatientName());
            productOrder.setApplyNumber(purchaseApplyVo.getApplyNumber());
            productOrder.setPurchaseNum(purchaseApplyVo.getPurchaseNum());
            productOrder.setProductId(purchaseApplyVo.getProductId());
            productOrder.setProductName(purchaseApplyVo.getProductName());
            productOrder.setPurchaseUrl(purchaseApplyVo.getProductUrl());
            productOrder.setProductEncoded(purchaseApplyVo.getProductEncoded());
            productOrder.setSupplierId(order.getSupplierId());
            productOrder.setSupplierName(order.getSupplierName());
            productOrder.setWarehouseId(order.getWarehouseId());
            productOrder.setPurchaseDetailId(purchaseApplyVo.getId());
            productOrder.setRemark(purchaseApplyVo.getRemark());
            productOrder.setWarehouseName(order.getWarehouseName());
            StringBuilder stringBuilder=new StringBuilder();
            productOrder.setProductParam(purchaseApplyVo.getProductParam());
            if(order.getPurchaseType()==3){
                productOrder.getPurchaseProductParamList().forEach(j->{
                    stringBuilder.append(j.getAttributeName()+":"+j.getAttributeParameter()+";");
                });
                productOrder.setProductParam(stringBuilder.toString());
            }
            productOrder.setUnit(purchaseApplyVo.getUnit());
            BigDecimal price = iPurchasePriceService.insertPurchasePrice(new PurchasePrice(purchaseApplyVo.getSupplierId(), purchaseApplyVo.getProductId(), order.getTenantId()));
            productOrder.setCostPrice(price);
            productOrder.setStatus(1);
            ProductCategoryVo productCategory = iProductService.getProductCategory(purchaseApplyVo.getProductId());
            if (Objects.nonNull(productCategory)) {
                productOrder.setBrandName(productCategory.getBrandName());
                productOrder.setProdName(productCategory.getProdName());
                productOrder.setProductCategory(productCategory.getProductCategory());
                productOrder.setManufacturer(productCategory.getManufacturer());
                productOrder.setRegistrationNumber(productCategory.getRegistrationNo());
            }
            productOrder.setDeptId(order.getDeptId());
            productOrder.setCreateTime(DateUtils.getNowDate());
            productOrder.setCreateBy(order.getCreateBy());
            productOrder.setTenantId(order.getTenantId());
            productOrder.setPurchaseOrderId(order.getId());
            productOrder.setWaitPurchaseNum(purchaseApplyVo.getPurchaseNum());
            productOrder.setProductUrlName(purchaseApplyVo.getProductUrlName());
            productOrder.setApplyNumber(purchaseApplyVo.getApplyNumber());
            productOrderList.add(productOrder);
            PurchaseProductApply purchaseProductApply = iPurchaseProductApplyService.selectPurchaseProductApplyById(purchaseApplyVo.getId());
            if(Objects.isNull(purchaseProductApply)){
                throw new ServiceException("生成采购单失败");
            }
            purchaseProductApply.setPurchaseNum(purchaseApplyVo.getPurchaseNum());
            purchaseProductApply.setPurchaseWarehouseName(purchaseApplyVo.getWarehouseName());
            purchaseProductApply.setPurchaseNo(order.getPurchaseNo());
            purchaseProductApply.setStatus(2);
            iPurchaseProductApplyService.updatePurchaseProductApply(purchaseProductApply);
            //更新采购申请状态
            int count = iPurchaseProductApplyService.count(new QueryWrapper<PurchaseProductApply>().eq("purchase_id", purchaseProductApply.getPurchaseId()).eq("status", 1));
            PurchaseApply purchaseApply = iPurchaseApplyService.getById(purchaseProductApply.getPurchaseId());
            purchaseApply.setPurchaseStatus(count==0?2:3);
            iPurchaseApplyService.updateById(purchaseApply);
        }
    }
    /**
     * 申请数据处理
     * @param order
     * @param productOrderList
     * @param purchaseApplyVoList
     */
    public void dataProductOrder(PurchaseOrder order,List<PurchaseProductOrder> productOrderList,List<PurchaseProductOrder> purchaseApplyVoList){
        for(PurchaseProductOrder purchaseApplyVo:purchaseApplyVoList) {
            PurchaseProductOrder productOrder = new PurchaseProductOrder();
            productOrder.setPatientId(purchaseApplyVo.getPatientId());
            productOrder.setPatientName(purchaseApplyVo.getPatientName());
            productOrder.setPurchaseNum(purchaseApplyVo.getPurchaseNum());
            productOrder.setProductId(purchaseApplyVo.getProductId());
            productOrder.setProductName(purchaseApplyVo.getProductName());
            productOrder.setProductEncoded(purchaseApplyVo.getProductEncoded());
            productOrder.setSupplierId(order.getSupplierId());
            productOrder.setSupplierName(order.getSupplierName());
            productOrder.setWarehouseId(order.getWarehouseId());
            productOrder.setWarehouseName(order.getWarehouseName());
            productOrder.setProductUrlName(purchaseApplyVo.getProductUrlName());
            productOrder.setPurchaseDetailId(purchaseApplyVo.getPurchaseDetailId());
            productOrder.setApplyNumber(purchaseApplyVo.getApplyNumber());
            StringBuilder stringBuilder=new StringBuilder();
            productOrder.setProductParam(purchaseApplyVo.getProductParam());
            if(order.getPurchaseType()==3){
                purchaseApplyVo.getPurchaseProductParamList().forEach(j->{
                    stringBuilder.append(j.getAttributeName()+":"+j.getAttributeParameter()+";");
                });
                productOrder.setProductParam(stringBuilder.toString());
            }
            productOrder.setUnit(purchaseApplyVo.getUnit());
            BigDecimal price = iPurchasePriceService.insertPurchasePrice(new PurchasePrice(order.getSupplierId(), purchaseApplyVo.getProductId(), order.getTenantId()));
            productOrder.setCostPrice(price);
            productOrder.setStatus(1);
            ProductCategoryVo productCategory = iProductService.getProductCategory(purchaseApplyVo.getProductId());
            if (Objects.nonNull(productCategory)) {
                productOrder.setBrandName(productCategory.getBrandName());
                productOrder.setProdName(productCategory.getProdName());
                productOrder.setProductCategory(productCategory.getProductCategory());
                productOrder.setManufacturer(productCategory.getManufacturer());
                productOrder.setRegistrationNumber(productCategory.getRegistrationNo());
            }
            productOrder.setDeptId(order.getDeptId());
            productOrder.setCreateTime(DateUtils.getNowDate());
            productOrder.setCreateBy(order.getCreateBy());
            productOrder.setTenantId(order.getTenantId());
            productOrder.setPurchaseOrderId(order.getId());
            productOrder.setWaitPurchaseNum(purchaseApplyVo.getPurchaseNum());
            productOrderList.add(productOrder);
        }
    }

    /**
     * 待入库列表
     * @param purchaseOrder
     * @return
     */
    @Override
    public List<WaitingListVo> getWaitingList(PurchaseOrder purchaseOrder) {
        return baseMapper.getWaitingList(purchaseOrder);
    }
}
